import { ref, onMounted } from "vue";

import { deepClone } from "@/utils/index.js";
import http from "@/api/http";
export const useBasicsTable = (config) => {
  const querys = ref({
    current: 1,
    size: 10,
  });
  const total = ref(0);
  const tableData = ref([]);
  const loading = ref(false);

  onMounted(() => {
    if (config && config.url) {
      tableList();
      // setInterval(() => {
      //   tableList();
      //   tableList();
      // }, 500);
    }
  });
  const tableList = async () => {
    loading.value = true;
    const params = {
      url: config.url,
      params: deepClone(querys.value),
    };
    if (config && config.getParams) {
      params.params = {
        ...params.params,
        ...config.getParams(),
      };
    }
    try {
      const res = await http.get(params);
      tableData.value = res.records || [];
      total.value = res.total;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  };
  const handleReset = () => {
    querys.value = {
      current: 1,
      size: 10,
    };
    tableList();
  };
  const handleSelect = () => {
    querys.value.current = 1;
    tableList();
  };
  const handleSizeChange = (val) => {
    querys.value.size = val;
    tableList();
  };
  const handleCurrentChange = (val) => {
    querys.value.current = val;
    tableList();
  };
  return {
    querys,
    total,
    tableData,
    loading,
    tableList,
    handleReset,
    handleSelect,
    handleSizeChange,
    handleCurrentChange,
  };
};
